import Vue from 'vue'
import Vuex from 'vuex'
import { fetchCityList, fetchList } from '../api'
Vue.use(Vuex)

export const SET_CITY_LIST = 'SET_CITY_LIST'
export const SET_LIST = 'SET_LIST'

export default new Vuex.Store({
  state: {
    // 选车页面数据
    cityList: [],
    list: []
  },
  mutations: {
    [SET_CITY_LIST](state, payload) {
      state.cityList = payload
    },
    [SET_LIST](state, payload) {
      state.list = payload
    }
  },
  actions: {
    async [SET_CITY_LIST]({ commit }) {
      // 请求数据
      const resp = await fetchCityList()
      // 处理原始数据
      const list = []
      resp.data.data.filter(item => item.type === '1001').forEach(item => {
        item = item.info
        const isExist = list.find(v => v.pinyin === item.pinyin)
        if(!isExist) {
          list.push({
            pinyin: item.pinyin,
            children: [item]
          })
        } else {
          isExist.children.push(item)
        }
      })
      // 保存
      commit(SET_CITY_LIST, list)
      console.log(list);
    },
    async [SET_LIST]({ commit }) {
      const resp = await fetchList()
      commit(SET_LIST, resp.data.data)
    }
  },
  modules: {
  }
})
